//
//  FriendDetailView.swift
//  ShouChong
//
//  Created by yw on 2024/9/24.
//

import SwiftUI

struct FriendDetailView: View {
    @State var heigth:CGFloat = 0.7 * kScreenHeight
    @State var offsetY:CGFloat = 0
    @State var currentDragOffsetY:CGFloat = 0
    @State var endingOffsetY: CGFloat = 0
    @Binding var showDetailView:Bool
    @State var currentModel:UserModel
    @State var showLoading:Bool = true
    @State var currentUserInfo:HistoryModel?
    
    var body: some View {
        ZStack {
            Color.black.opacity(0.2)
                .ignoresSafeArea()
                .onTapGesture {
                    close()
                }
           
            RoundedRectangle(cornerRadius: 20)
                .fill(Color("color_bg"))
                .frame(height:  heigth)
                .overlay(alignment: .center, content: {
                    if showLoading {
                        ProgressView()
                    } else {
                        detailView
                    }
                })
                .overlay(alignment: .top) {
                    RoundedRectangle(cornerRadius: 3)
                        .fill(Color.black)
                        .frame(width: 60,height: 6)
                        .padding(.top,8)
                    
//                    Text("\(currentDragOffsetY)")
                }
                .offset(y: 0.15 * kScreenHeight)
                .offset(y: currentDragOffsetY)
                .offset(y: endingOffsetY)
                .gesture(
                    DragGesture().onChanged({ value in
                        withAnimation(.spring()) {
                            if value.translation.height < 0 {
                                return
                            }
                            currentDragOffsetY = value.translation.height
                        }
                    }).onEnded({ value in
                        withAnimation(.spring()) {
                            if currentDragOffsetY > 300{
                                endingOffsetY = heigth
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                    showDetailView.toggle()
                                }
                            } else {
                                endingOffsetY = 0
                                currentDragOffsetY = 0
                            }
                        }
                    })
                )
        }.onAppear{
            getActinveUserInfo(uid: currentModel.uid)
        }
    }
    
    var detailView:some View {
        VStack {
            VStack {
                Image(uiImage: currentModel.image.imageFromBase64 ?? UIImage())
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width:100,height: 100)
                    .cornerRadius(50)
                Text(currentModel.name)
                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
            }
            .padding(.vertical,20)
            .padding(.bottom,20)
            
            HStack {
                Text("最新使用记录")
                    .modifier(MainTextModifier(fontSize: 13, fontWeight: .light, foreColor: Color("color_text_black")))
                Spacer()
            }
            
            HStack {
                Spacer()
                createItem(imageName:"⏳", bgColor: "color_home_01", title:"时长(秒)",value: currentUserInfo?.duration ?? "0")
                Spacer()
                Divider().frame(height: 60)
                Spacer()
                createItem(imageName:"💪🏻", bgColor: "color_home_03", title:"次数",value: currentUserInfo?.count ?? "0")
                Spacer()
                Divider().frame(height: 60)
                Spacer()
                createItem(imageName:"❤️", bgColor: "color_home_02", title:"心率",value: currentUserInfo?.heartRate ?? "0")
                Spacer()
            }
            .padding(.vertical,20)
            Spacer()
            
            
        }.padding(20)
    }
    
    private func createItem(imageName:String,bgColor:String,title:String,value:String) -> some View {
        VStack {
            Text(imageName)
                .frame(width: 48,height: 48)
                .background(Color(bgColor))
                .cornerRadius(24)
            
            Text(value)
                .modifier(MainTextModifier(fontSize: 20, fontWeight: .bold, foreColor: Color("color_text_black")))
                .padding(.vertical,6)
            Text(title)
                .modifier(MainTextModifier(fontSize: 13, fontWeight: .light, foreColor: Color("color_text_black")))
                        
        }
    }
    
    private func close() {
        
        withAnimation(.spring()) {
            endingOffsetY = heigth
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                showDetailView.toggle()
            }
        }
    }
    
    private func getActinveUserInfo(uid:String) {
        let sendData = ["uid":uid]
        showLoading = true
        YWNetworkTool.share().requestJson(url: "user/getActiveUsersInfo", parameters: sendData) { res in
            DPrint(res)
            showLoading = false
            guard let results = res as? [String:Any],
                  let status = results["status"] as? Int,
                  let message = results["message"] as? String,
                  let data = results["data"] as? [[String:Any]],
                  let jsonData = try? JSONSerialization.data(withJSONObject: data)
                    else
            {
                YWToast.show(text: "获取用户信息失败")
                return
            }
            if status == 200 {
                do {
                    let models = try JSONDecoder().decode([HistoryModel].self, from: jsonData)
                    if models.count > 0 {
                        currentUserInfo = models.first
                    }
                } catch {
                    YWToast.show(text: "获取用户信息失败")
                }
                
            }else {
                YWToast.show(text: message)
            }
            
        } responseFailBlock: { error, code in
            YWToast.show(text: "获取用户信息失败")
        }
    }
}
